import { defineStore } from 'pinia'
import type { UserState } from '@/store/modules/types/type.ts'
import { GET_TOKEN, REMOVE_TOKEN, SET_TOKEN } from '@/utils/token.ts'
import { constantRoutes, asyncRoutes, anyRoute } from '@/router/routes.ts'
import { reqLogout, reqUserInfo } from '@/api/user'
import router from '@/router'
//@ts-expect-error ts忽略lodash的类型检测
import cloneDeep from 'lodash/cloneDeep'
import type { Userinfo } from '@/api/user/type.ts'
import type { ResponseData } from '@/api/type.ts'

const filterAsyncRoutes = (asyncRoutes: any[], routes: any[]) => {
  return asyncRoutes.filter((item: any) => {
    if (routes.includes(item?.name)) {
      if (item.children && item.children.length > 0) {
        item.children = filterAsyncRoutes(item.children, routes)
      }
      return true
    }
  })
}

const useUserStore = defineStore('User', {
  state: (): UserState => {
    return {
      token: GET_TOKEN(),
      routes: [],
      avatar: '',
      username: '',
      buttons: [],
    }
  },
  actions: {
    updateToken(token: string) {
      SET_TOKEN(token)
      this.token = GET_TOKEN()
    },
    async userLogout() {
      const { code, message }: ResponseData<any> = await reqLogout()
      if (code === 200) {
        this.clear()
        return true
      } else {
        return Promise.reject(new Error(message))
      }
    },
    async updateUserInfo() {
      const { code, data, message }: ResponseData<Userinfo> =
        await reqUserInfo()
      if (code === 200) {
        this.avatar = data?.avatar
        this.username = data?.name
        this.buttons = data?.buttons
        const userAsyncRoutes = filterAsyncRoutes(
          cloneDeep(asyncRoutes),
          data?.routes,
        )
        this.routes = [...constantRoutes, ...userAsyncRoutes, anyRoute]
        ;[...userAsyncRoutes, anyRoute].forEach((route) => {
          router.addRoute(route)
        })
        return true
      } else {
        return Promise.reject(new Error(message))
      }
    },
    clear() {
      this.token = ''
      REMOVE_TOKEN()
      this.avatar = ''
      this.username = ''
      this.routes = []
    },
  },
  getters: {},
})

export default useUserStore
